var pc = null;
export var pcConnected = false;
var clentAudio = null;

function setOnlineStatus(msg) {
  console.log("connectionstatechange", msg);
}

/*************  ✨ Codeium Command ⭐  *************/
/**
 * Negotiate a WebRTC connection.
 *
 * 1. Add transceivers for video and audio.
 * 2. Set up an event listener for connection state changes.
 * 3. Create and set a local offer.
 * 4. Gather ICE candidates.
 * 5. Send the offer to the server.
 * 6. Set the remote description from the server's response.
 *
 * @returns {Promise} Resolves when the negotiation is complete.
 */
/******  467a1060-f536-4382-b684-5684b51a5bc8  *******/ function negotiate() {
  return new Promise((resolve, reject) => {
    pc.addTransceiver("video", { direction: "recvonly" });
    pc.addTransceiver("audio", { direction: "recvonly" });
    pc.addEventListener(
      "connectionstatechange",
      (event) => {
        switch (pc.connectionState) {
          case "new":
          case "connecting":
            setOnlineStatus("Connecting…");
            break;
          case "connected":
            setOnlineStatus("Online");
            pcConnected = true;
            break;
          case "disconnected":
            setOnlineStatus("Disconnecting…");
            pcConnected = false;
            break;
          case "closed":
            setOnlineStatus("Offline");
            break;
          case "failed":
            setOnlineStatus("Error");
            break;
          default:
            setOnlineStatus("Unknown");
            break;
        }
      },
      false
    );
    pc.createOffer()
      .then((offer) => {
        return pc.setLocalDescription(offer);
      })
      .then(() => {
        // wait for ICE gathering to complete
        return new Promise((resolve) => {
          if (pc.iceGatheringState === "complete") {
            resolve();
          } else {
            const checkState = () => {
              console.log("pc.iceGatheringState", pc.iceGatheringState);
              if (pc.iceGatheringState === "complete") {
                pc.removeEventListener("icegatheringstatechange", checkState);
                resolve();
              }
            };
            pc.addEventListener("icegatheringstatechange", checkState);
          }
        });
      })
      .then(() => {
        var offer = pc.localDescription;
        return fetch("/api2/offer", {
          body: JSON.stringify({
            sdp: offer.sdp,
            type: offer.type,
          }),
          headers: {
            "Content-Type": "application/json",
          },
          method: "POST",
        });
      })
      .then((response) => {
        return response.json();
      })
      .then((answer) => {
        return pc.setRemoteDescription(answer);
      })
      .then(() => {
        setTimeout(()=> {
          resolve();
        },2000)
      })
      .catch((e) => {
        reject(e);
      });
  });
}

export function start(preVideo) {
  return new Promise((resolve, reject) => {
    var config = {
      sdpSemantics: "unified-plan",
    };

    if (document.getElementById("use-stun").checked) {
      // config.iceServers = [{ urls: ['stun:stun.l.google.com:19302'] }];
    }

    pc = new RTCPeerConnection(config);

    // connect audio / video
    pc.addEventListener("track", (evt) => {
      if (evt.track.kind == "video") {
        preVideo.srcObject = evt.streams[0];
      } else {
        clentAudio = document.getElementById("audio")
        clentAudio.srcObject = evt.streams[0];
        clentAudio.play();
      }
    });

    negotiate()
      .then(()=> {
        resolve()
      })
      .catch((e) => {
        reject(e);
      });
  });
}

export function stop() {
  // close peer connection
  setTimeout(() => {
    pc.close();
  }, 500);
}
